package view 
{
	import caurina.transitions.Tweener;
	import events.AlbumEvent;
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.AntiAliasType;
	import flash.text.GridFitType;
	import flash.text.TextField;
	import model.MainModel;
	import view.components.BaseImage;
	import view.containers.PhotoContainer;

	public class MainView extends StartScreenTemplate
	{
		private var img:BaseImage = new BaseImage();
		private var images:Sprite = new Sprite()
		
		public function MainView() {
			topPanel.caption.gridFitType = GridFitType.PIXEL;
			topPanel.caption.antiAliasType = AntiAliasType.ADVANCED
			playBtn.addEventListener(MouseEvent.CLICK, mouseHandler);
			images.x = width * 0.5;
			images.y = height * 0.5;
			addChildAt(images, 1);
			addEventListener(Event.ADDED_TO_STAGE, onAdded);
		}
		private function onAdded(e:Event):void {
			removeEventListener(Event.ADDED_TO_STAGE, onAdded);
			Main.instance.acontroller.addEventListener(AlbumEvent.ALBUM_INITED, onAlbumInited);
			topPanel.gotoAndStop(MainModel.user.sex);
			topPanel.caption.text = MainModel.user.name;
			img.addEventListener(Event.INIT, onPhotoLoaded);
		}
		private function onPhotoLoaded(e:Event):void {
			var bmp:PhotoContainer = new PhotoContainer(img.content.bitmapData.clone());
			var radiusX:Number = 150;
			var radiusY:Number = 110;
			bmp.scaleX = bmp.scaleY = 0.1;
			var angle:Number = Math.PI / ((MainModel.albums.length) / 2) * images.numChildren;
			var tox:Number = radiusX * Math.cos(angle);
			var toy:Number = radiusY * Math.sin(angle);
			Tweener.addTween(bmp, { x:tox, y:toy, time:0.5, scaleX:1, scaleY:1, rotation:Math.random() * 60 - 30 } );
			images.addChild(bmp);
		}
		private function onAlbumInited(e:AlbumEvent):void {
			img.load(e.album.thumbPhoto.src_small);
		}
		private function mouseHandler(e:MouseEvent):void {
			img.destroy();
			playBtn.removeEventListener(MouseEvent.CLICK, mouseHandler);
			playBtn.mouseEnabled = false;
			Main.instance.acontroller.removeEventListener(AlbumEvent.ALBUM_INITED, onAlbumInited);
			for (var i:int = 0; i < images.numChildren; i++) {
				var child:DisplayObject = images.getChildAt(i);
				var angle:Number = Math.atan2(child.x, child.y);
				var tox:Number = 300 * Math.sin(angle);
				var toy:Number = 300 * Math.cos(angle);
				Tweener.pauseTweens(child);
				Tweener.addTween(child, { x:tox, y:toy, scaleX:1.5, scaleY:1.5, alpha:0, time:0.5, rotation:angle * (180 / Math.PI) } );
			}
			Tweener.addTween(topPanel, { y: -topPanel.height, alpha:0, time:0.5 } );
			Tweener.addTween(logo, { y: height + logo.height, alpha:0, time:0.5 } );
			Tweener.addTween(this, { delay:0.3, time:0.5, alpha:0, onComplete:switchToAlbums } );
		}		
		
		private function switchToAlbums():void {
			Main.instance.switchToScreen(2);
		}
	}
}